package com.qst.controller;

import com.qst.*;
import com.qst.entity.*;
import com.qst.service.AssessmentService;
import com.qst.service.ExamService;
import com.qst.service.QuestionService;
import com.qst.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@RequestMapping("/exam")
@SuppressWarnings("all")
@Controller
public class ExamController  extends BaseServlet {

    @Autowired
    @Qualifier("assessmentServiceSsmImpl")
    private AssessmentService assessmentService;

    @Autowired
    @Qualifier("examServiceSsmImpl")
    private ExamService examService;

    @Autowired
    @Qualifier("scheduleServiceSsmImpl")
    private ScheduleService scheduleService;

    @Autowired
    @Qualifier("questionServiceSsmImpl")
    private QuestionService questionService;

//    private QuestionService questionService = ServiceFactory.getService(QuestionService.class);

    @RequestMapping("/begin.action")
    public String begin(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        TestPersonnel testPersonnel = (TestPersonnel) req.getSession().getAttribute(Constant.
                CURRENT_TESTPERSONNEL);
        int scheduleId = RequestUtil.getInt(req, "id");
        try {
            // 生成某个考生的试题：包含考生信息和试题集合
            Exam exam = examService.begin(testPersonnel, scheduleId);
            req.getSession().setAttribute(Constant.CURRENT_EXAM, exam);
//            WebUtil.redirect(req, resp, "/exam/exam.action");
            return "redirect:/exam/exam.action";
        } catch (ExamException ex) {
            ex.printStackTrace();
            addError(req, ex.getMessage());
//            WebUtil.redirect(req, resp, "/exam/list.action");
            return "redirect:/exam/list.action";
        }


    }

    @RequestMapping("/end.action")
    public String end(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Exam exam = (Exam) req.getSession().getAttribute(Constant.CURRENT_EXAM);
        try {
            examService.end(exam);
            StringBuffer stf = new StringBuffer();
            stf.append("../analysis/");
            stf.append(exam.getResult());
            stf.append(".jsp");
            req.setAttribute("examresult", stf.toString());
            req.setAttribute("score",exam.getResult());
        } catch (ExamException ex) {
            ex.printStackTrace();
            req.setAttribute("score", "您未能成功交卷，请重新交卷");
        }
//        WebUtil.forward(req, resp, "/exam/end.jsp");
        return "/exam/end";
    }

    @RequestMapping("/exam.action")
    public String exam(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Exam exam = (Exam) req.getSession().getAttribute(Constant.CURRENT_EXAM);

        int[] answer = RequestUtil.getIntArray(req, "answer");

        ExamQuestion eq = exam.getQuestion();
        eq.setAnswer(answer);

        int index = RequestUtil.getInt(req, "index");// -1：前一题，－２　后一题，　其他：指定下标

        if (index == -3)  //交卷
        {
//            WebUtil.redirect(req, resp, "/exam/end.action");
            return"redirect:/exam/end.action";
        }

        if (index == -2) // 后一题
        {
            exam.setQuestionIndex(exam.getQuestionIndex() + 1);
        } else if (index == -1)// 前一题
        {
            exam.setQuestionIndex(exam.getQuestionIndex() - 1);
        } else // 指定下标的题
        {
            exam.setQuestionIndex(index);
        }
        eq = exam.getQuestion();

        // 第一次加载题目时，题目没有选项，因为生成题目时，没有生成选项
        List<Choice> choices = eq.getQuestion().getChoices();
        if (choices == null) {
            choices = questionService.findChoices(eq.getQuestionId());
            Collections.shuffle(choices);
            eq.getQuestion().setChoices(choices);
        } else {
            // 确定哪个choice在页面上应该被选中
            for (Choice ch : choices) {
                ch.getExtras().remove("checked");
                if (eq.getAnswer() != null) {
                    for (int ans : eq.getAnswer()) {
                        if (ans == ch.getId()) {
                            ch.getExtras().put("checked", "checked");
                            break;
                        }
                    }
                }
            }

        }
//        WebUtil.forward(req, resp, "/exam/exam.jsp");
        return "/exam/exam";
    }

    @RequestMapping("/list.action")
    public String list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        TestPersonnel stu = (TestPersonnel) req.getSession().getAttribute(Constant.CURRENT_TESTPERSONNEL);
        List<Schedule> scheduleList = examService.findScheduleByTestPersonnel(stu);

        req.setAttribute("scheduleList", scheduleList);
//        WebUtil.forward(req, resp, "/exam/list.jsp");
        return "/exam/list";
    }

    @RequestMapping("/result.action")
    public String result(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int resultId = RequestUtil.getInt(req, "id");
        Exam exam = examService.getExamResult(resultId);
        StringBuffer stf=new StringBuffer();
        stf.append("../analysis/");
        stf.append(exam.getResult());
        stf.append(".jsp");
        req.setAttribute("examresult", stf.toString());
        req.setAttribute("exam",exam);
//        WebUtil.forward(req, resp, "/exam/result.jsp");
        return  "/exam/result";
    }



}
